package pt.mauromad.guias.service;

import static pt.mauromad.guias.utils.CastUtils.cast;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import pt.mauromad.guias.dao.AddressDao;

@Service
public class AddressService extends DaoService<AddressDao, Long> {
	public AddressService() {
		super(AddressDao.class);
	}

	public AddressDao get(Long id, Long companyId) {
		AddressDao addr = get(id);

		if (addr.getCompany().getId() == companyId)
			return addr;

		throw new IllegalArgumentException();
	}

	public List<AddressDao> byAccount(Long accountId) {
		Criteria c = sessionFactory.getObject().getCurrentSession().createCriteria(AddressDao.class, "address");
		c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		c.createAlias("address.company", "company");
		c.createAlias("company.account", "account");
		c.add(Restrictions.eq("account.id", accountId));
		return cast(c.list());
	}

	public List<AddressDao> byAccount(Long accountId, boolean enabled) {
		Criteria c = sessionFactory.getObject().getCurrentSession().createCriteria(AddressDao.class, "address");
		c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		c.createAlias("address.company", "company");
		c.createAlias("company.account", "account");
		c.add(Restrictions.eq("account.id", accountId));
		c.add(Restrictions.eq("company.enabled", enabled));
		c.add(Restrictions.eq("address.enabled", enabled));
		return cast(c.list());
	}
}
